#include <stdlib.h>

#include "tnet.h"


int main(int argc, char **argv)
{
  TnetContext ctx;
  ctx.malloc = malloc;
  ctx.logfd = stderr;
  //printf("logfd: %d", ctx.logfd);

  if (argc < 2) {
    printf("No actions");
    exit(1);
  }

  char* action = argv[1];

  if (strcmp(action, "dump-dict") == 0) {
    Pair p, p2;
    p.key = tnet_string_to_chunk("one");
    p.value = tnet_string_to_chunk("three");
    p.next = NULL;

    p2.key = tnet_string_to_chunk("four");
    p2.value = tnet_string_to_chunk("six");
    p2.next = &p;

    Buffer out;  // data allocated by tnet_dump_dict
    tnet_dump_dict(&ctx, &p2, &out);

    printf("OUT %s\n", out.data);
    printf("OUT char %d\n", *out.data);
    printf("OUT length %d\n", out.len);

  } else if (strcmp(action, "read") == 0) {

    Chunk c;
    if (!tnet_read(&ctx, stdin, &c)) {
      printf("Error reading\n");
      exit(1);
    }
    printf("buf %s\n", c.payload.data);
    printf("len %d\n", c.payload.len);
    printf("tag %c\n", c.tag);

    // tnet_read allocates memory that we have to free.
    tnet_free_chunk(c);

  } else if (strcmp(action, "read-dict") == 0) {
    Chunk c;
    if (!tnet_read(&ctx, stdin, &c)) {
      printf("Error reading");
      exit(1);
    }
    printf("buf %s\n", c.payload.data);
    printf("len %d\n", c.payload.len);
    printf("tag %c\n", c.tag);

    // Now parse it into a dict.  Pair instances are allocated.  But Buffer
    // shares the underlying storage.
    Pair* pairs;
    if (!tnet_parse_dict_chunks(&ctx, c.payload, &pairs)) {
      printf("Error parsing dict");
      exit(1);
    }

    printf("-------------\n");
    tnet_print_pairs(pairs);
    printf("-------------\n");

    Chunk c2;
    if (tnet_pairs_getchunk(pairs, "foo", &c2)) {
      printf("CHUNK for foo\n");
      tnet_print_buf(c2.payload);
    } else {
      printf("NOt found\n");
    }

    // tnet_read allocates memory that we have to free.
    tnet_free_chunk(c);
    // tnet_parse_dict allocates memory we have to free.
    tnet_free_pairs(pairs);

  } else {
    printf("Unknown action %s\n", action);
  }
  return 0;
}

